package nc.bs.uapbd.utli;



import java.text.SimpleDateFormat;
import java.util.Date;

import nc.bs.dao.DAOException;
import nc.jdbc.framework.generator.IdGenerator;
import nc.jdbc.framework.generator.SequenceGenerator;
import nc.vo.pub.SuperVO;
import nc.vo.pub.lang.UFDate;


public class CBaseDAO {
	public static int insertVO(SuperVO superVO) throws DAOException{
		IdGenerator idGenerator = new SequenceGenerator();
		 //superVO.setAttributeValue(superVO.getPKFieldName(), idGenerator.generate());
		
		String sql= getInsertSQL(superVO.getTableName(), superVO.getAttributeNames(),superVO);
		System.out.println();
		return BaseDAOUtliJM.getBase().executeUpdate(sql);
	}  
	
	public static int updateVO(SuperVO superVO)throws DAOException{
		String sql= getUpdateSQL(superVO.getTableName(), superVO.getAttributeNames(),superVO);
		return BaseDAOUtliJM.getBase().executeUpdate(sql);
	};
	
	public static String getInsertSQL(String table, String[] names,SuperVO superVO){
		StringBuffer buffer = new StringBuffer("INSERT INTO " + table + " (");
		for (int i = 0; i < names.length; i++) {
			if (superVO.getAttributeValue(names[i])!=null){
				buffer.append(names[i] + ","); 
			}
		}
		buffer.setLength(buffer.length() - 1);
		buffer.append(") VALUES (");
		for (int i = 0; i < names.length; i++) {
			if (superVO.getAttributeValue(names[i])!=null){
				buffer.append("'"+superVO.getAttributeValue(names[i])+"',"); 
			}
		}
		buffer.setLength(buffer.length() - 1);
		buffer.append(")");
    return buffer.toString();
  }
	

	public static String getUpdateSQL(String tableName, String[] names, SuperVO superVO){
	     StringBuffer sql = new StringBuffer("UPDATE " + tableName + " SET  ");
	     for (int i = 0; i < names.length; i++) {
	       if (superVO.getAttributeValue(names[i])!=null&&!names[i].equals(superVO.getPKFieldName())){
	         sql.append(names[i] + "='"+superVO.getAttributeValue(names[i])+"',"); 
	         }
	     }
	     sql.setLength(sql.length() - 1);
	     sql.append(" WHERE ").append(superVO.getPKFieldName()).append("= '"+superVO.getAttributeValue(superVO.getPKFieldName())+"'");
	     return sql.toString();
	 }
	

	public static void main(String[] args) {
		UFDate ufDate =new UFDate();
		SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
		dateFormat.format(new Date());
	}
}
